package com.atguigu.gmall.component;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jerry.Su
 * @Date 2022/2/21 9:12
 */
public class RequestContextStore {

    private final ThreadLocal<Map<String, String>> copyOnThreadLocal = ThreadLocal.withInitial(HashMap::new);

    private final static Object lock = new Object();

    public static final String TRACE_ID_KEY = "x-trace-id";

    private RequestContextStore() {
    }

    private static RequestContextStore singleton = null;

    public static RequestContextStore getInstance() {
        if (singleton == null) {
            singleton = new RequestContextStore();
        }
        return singleton;
    }


    public void setTraceId(String traceId) {
        this.set(TRACE_ID_KEY, traceId);
    }

    public String getTraceId() {
        return get(TRACE_ID_KEY);
    }

    public void set(String key, String value) {
        if (key == null) {
            throw new IllegalArgumentException("key 不能为null");
        }
        Map<String, String> map = copyOnThreadLocal.get();
        synchronized (lock) {
            map.put(key, value);
        }
    }

    public String get(String key) {
        Map<String, String> map = copyOnThreadLocal.get();
        return map.get(key);
    }

    public String removeTraceId() {
        return this.remove(TRACE_ID_KEY);
    }

    public String remove(String key) {
        return copyOnThreadLocal.get().remove(key);
    }

    public void clear() {
        copyOnThreadLocal.remove();
    }


    public Map<String, String> getCopyOfContextMap() {
        Map<String, String> hashMap = this.copyOnThreadLocal.get();
        return hashMap == null ? null : new HashMap<>(hashMap);
    }

    public void setContextMap(Map<String, String> contextMap) {
        Map<String, String> newMap = Collections.synchronizedMap(new HashMap<>());
        newMap.putAll(contextMap);
        this.copyOnThreadLocal.set(newMap);
    }
}
